<template>
  <el-card header="地址信息" class="form-section">
    <el-form-item label="省市区" prop="region">
      <RegionCascader
        v-model="regionValue"
        placeholder="请选择省市区"
        clearable
        style="width: 100%"
        @change="handleRegionChange"
        @focus="handleFocus"
        @blur="handleBlur"
      />
    </el-form-item>

    <el-form-item label="详细地址" prop="address">
      <el-input
        v-model="formData.address"
        placeholder="请输入详细地址（街道、门牌号等）"
        clearable
        maxlength="255"
        show-word-limit
        @focus="handleFocus"
        @blur="handleBlur"
      />
    </el-form-item>
  </el-card>
</template>

<script setup lang="ts">
  import { ref, computed, watch } from 'vue'
  import RegionCascader from '@/components/business/region/RegionCascader.vue'

  const props = defineProps({
    modelValue: {
      type: Object,
      default: () => ({}),
    },
  })

  const emit = defineEmits(['change'])

  // 直接使用props.modelValue，避免尝试重新赋值整个对象
  const formData = computed(() => props.modelValue)

  // 省市区级联选择器值（字符串格式：province/city/district）
  const regionValue = ref<string | null>(null)

  // 防止标签点击事件标记
  const isLabelClicked = ref(false)

  // 监听modelValue变化，初始化regionValue
  watch(
    () => props.modelValue,
    newVal => {
      if (newVal.province && newVal.city && newVal.district) {
        regionValue.value = `${newVal.province}/${newVal.city}/${newVal.district}`
      } else {
        regionValue.value = null
      }
    },
    { immediate: true }
  )

  // 处理标签点击事件
  const handleLabelClick = () => {
    console.log('地址信息标签被点击，标记为标签点击')
    isLabelClicked.value = true

    // 延迟重置标记，给其他事件时间处理
    setTimeout(() => {
      isLabelClicked.value = false
    }, 100)
  }

  // 处理地区变化
  const handleRegionChange = (value: string | null, selectedOptions: any[]) => {
    console.log('地区变化处理', value)

    if (value) {
      // 解析字符串格式：province/city/district
      const parts = value.split('/')
      formData.value.province = parts[0] || ''
      formData.value.city = parts[1] || ''
      formData.value.district = parts[2] || ''

      emit('change', { field: 'region', value })
    } else {
      // 清空地区信息
      formData.value.province = ''
      formData.value.city = ''
      formData.value.district = ''
    }
  }

  // 处理控件聚焦事件
  const handleFocus = (event: any) => {
    console.log('地址信息控件聚焦事件', event)
    if (isLabelClicked.value) {
      console.log('标签点击引起的地址控件聚焦事件，已屏蔽')
    }
  }

  // 处理控件失焦事件
  const handleBlur = (event: any) => {
    console.log('地址信息控件失焦事件', event)
  }
</script>

<style scoped>
  .form-section {
    margin-bottom: 20px;
  }

  /* 防止标签点击的样式方案 */
  :deep(.el-form-item__label) {
    cursor: default;
    user-select: none;
  }

  /* 级联选择器标签样式 */
  :deep(.el-cascader .el-input__inner) {
    user-select: none;
  }

  /* 输入框标签样式 */
  :deep(.el-input .el-input__inner) {
    user-select: none;
  }
</style>
